package com.ebupt.migu.music.strategy.service.impl;

import com.alibaba.fastjson.JSON;
import com.ebupt.migu.music.common.entity.ResultObject;
import com.ebupt.migu.music.common.exception.MyException;
import com.ebupt.migu.music.common.exception.StatusEnum;
import com.ebupt.migu.music.common.util.DateUtil;
import com.ebupt.migu.music.redis.service.RedisService;
import com.ebupt.migu.music.strategy.entity.StrategyDTO;
import com.ebupt.migu.music.strategy.entity.StrategyInfo;
import com.ebupt.migu.music.strategy.mapper.ProvinceStrategyMapper;
import com.ebupt.migu.music.strategy.mapper.StrategyMapper;
import com.ebupt.migu.music.strategy.service.ProvinceStrategyService;
import com.ebupt.migu.music.system.entity.SysUser;
import com.ebupt.migu.music.userGroup.entity.UserGroupInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description: 分省运营策略管理业务实现类
 *
 * @author lemon
 * @since 2022-09-14 11:13
 */
@Service
@Slf4j
public class ProvinceStrategyServiceImpl implements ProvinceStrategyService {

    @Resource
    private ProvinceStrategyMapper provinceStrategyMapper;

    @Resource
    private StrategyMapper strategyMapper;

    @Resource
    private RedisService redisService;

    @Override
    public ResultObject<List<StrategyInfo>> queryMessageIssuedStatus(StrategyDTO strategyDTO) {
        log.info("查询条件：{}", strategyDTO);
        if (!StringUtils.hasText(strategyDTO.getPlatformId().toString())) {
            throw new MyException(StatusEnum.BUSINID, "平台标识为空");
        }
        int total;
        List<StrategyInfo> strategyInfos;
        try {
            total = provinceStrategyMapper.queryStrategyTotal(strategyDTO);
            strategyInfos = provinceStrategyMapper.queryMessageIssuedStatus(strategyDTO);
        } catch (Exception e) {
            log.info("策略查询失败：{}", e.getMessage());
            throw new MyException(StatusEnum.BUSINID, "查询策略失败");
        }
        if (strategyInfos.size() > 0) {
            strategyInfos.forEach(s -> {
                String keyName = s.getExecuteTime() != null ?
                        s.getStrategyId() + "_" + DateUtil.parseDateToStr(s.getExecuteTime(), DateUtil.DATE_FORMAT_YYYYMMDD) + "_incr" :
                        s.getStrategyId() + "_" + "_incr";
                log.info("短信下发进度key值：{}", keyName);
                // Redis中不存在指定key，返回-1
                Object progress = redisService.exists(keyName) ? redisService.get(keyName) : -1;
                log.info("{}策略下发进度：{}", s.getStrategyId(), progress);
                s.setProgress(progress);
            });
        }
        return new ResultObject<>(StatusEnum.SUCCESS.getCode(), "策略查询成功，总条数：" + total, strategyInfos);
    }

    @Override
    public ResultObject<String> addMessageStrategy(StrategyInfo strategyInfo) {
        log.info("短信策略新建信息：{}", strategyInfo);
        // 平台标识不可为空
        if (null == strategyInfo.getPlatformId()) {
            throw new MyException(StatusEnum.BUSINID, "平台标识不可为空");
        }
        // 策略名称不可为空
        if (null == strategyInfo.getStrategyName()) {
            throw new MyException(StatusEnum.BUSINID, "策略名称不可为空");
        }
        // 策略名称不可重复
        String strategyName = strategyInfo.getStrategyName().trim();
        Map<String, Object> strMap = new HashMap<>(1);
        strMap.put("strategyName", strategyName);
        boolean isExist = strategyMapper.isExist(strMap);
        if (isExist) {
            throw new MyException(StatusEnum.STRATEGY_NAME_EXIST, strategyName + "的策略名称已存在");
        }
        // 客群信息判断
        UserGroupInfo userGroupInfo = provinceStrategyMapper.findCrowdByGroupId(strategyInfo.getGroupId());
        if (userGroupInfo == null) {
            throw new MyException(StatusEnum.BUSINID, "当前客群不存在");
        }
        // 短信内容不可为空
        if (null == strategyInfo.getSmsContent()) {
            throw new MyException(StatusEnum.BUSINID, "短信内容不可为空");
        }
        // 登录人手机号不可为空
        if (null == strategyInfo.getCreatorPhone()) {
            throw new MyException(StatusEnum.USERNAME_ERR, "用户登录信息为空");
        }
        // 赋值用户信息
        SysUser sysUser = provinceStrategyMapper.queryUserByMobile(strategyInfo.getCreatorPhone());
        if (sysUser == null) {
            throw new MyException(StatusEnum.USERNAME_ERR, "用户不存在");
        }
        strategyInfo.setCreatorId(sysUser.getLoginName());
        strategyInfo.setCreatorName(sysUser.getUserName());
        strategyInfo.setCreatorDepartment(sysUser.getDeptName());
        strategyInfo.setCreatorEmail(sysUser.getEmail());

        // 其他所需信息赋值
        strategyInfo.setStrategyName(strategyName);
        strategyInfo.setGroupName(userGroupInfo.getUserGroupName());
        strategyInfo.setStrategyId("DX" + DateUtil.parseDateToStr(new Date(), DateUtil.DATE_TIME_FORMAT_YYYYMMDDHHMISSSSS));
        strategyInfo.setStrategyGroupId("SG" + DateUtil.parseDateToStr(new Date(), DateUtil.DATE_TIME_FORMAT_YYYYMMDDHHMISS));
        strategyInfo.setStrategyType((byte) 1);
        strategyInfo.setExecuteStatus((byte) 3);

        String constructionJson = JSON.toJSONString(strategyInfo);
        strategyInfo.setConstructionJson(constructionJson);
        try {
            provinceStrategyMapper.addMessageStrategy(strategyInfo);
        } catch (Exception e) {
            log.info("{}的创建策略失败：{}", strategyName, e);
            throw new MyException(StatusEnum.ERROR, strategyName + "的创建策略失败");
        }
        return new ResultObject<>(StatusEnum.SUCCESS.getCode(), "短信策略创建成功", strategyInfo.getStrategyId());
    }
}
